package com.oppo.action;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.ui.MessageType;
import com.oppo.pojo.DataCenter;

import java.text.SimpleDateFormat;

/**
 * @author steve
 * @since 2022-01-01 15:41
 */

public class Timestamp extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 获取当前编辑器对象
        Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
        // 获取选择的数据模型
        SelectionModel selectionModel = editor.getSelectionModel();
        // 获取当前选择的文本
        DataCenter.SELECTED_TEXT = selectionModel.getSelectedText();

        if (DataCenter.SELECTED_TEXT == null) {
            notify("请先选择数据！");
            throw new RuntimeException("请先选择数据！");
        }

        long timestamp;
        try {
            timestamp = Long.parseLong(DataCenter.SELECTED_TEXT);
        } catch (NumberFormatException numberFormatException) {
            notify("数据无法转成Long类型");
            throw new RuntimeException("数据无法转成Long类型");
        }
        // System.out.println("timestamp = " + timestamp);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 判断时间戳的字符长度：10 | 13
        int length = DataCenter.SELECTED_TEXT.length();
        if (length == 10) {
            String dateStr = sdf.format(timestamp * 1000);
            notify(dateStr);
        } else if (length == 13) {
            String dateStr = sdf.format(timestamp);
            notify(dateStr);
        } else {
            notify("选择的时间戳位数应10位或13位");
        }
        // System.out.println("dateStr = " + dateStr);
    }

    private void notify(String showInfo) {
        NotificationGroup notificationGroup = new NotificationGroup("testId", NotificationDisplayType.BALLOON, false);
        /*
          content: 通知内容
          type   : 通知的类型，warning,info,error
         */
        Notification notification = notificationGroup.createNotification(DataCenter.SELECTED_TEXT + "=" + showInfo, MessageType.INFO);
        Notifications.Bus.notify(notification);
    }

}
